import Cache from '@/util/cache.js'
import md5 from 'js-md5'
import base64 from 'js-base64'

function sortKeys(x) {
	if (typeof x !== 'object' || !x) {
		return x;
	}
	if (Array.isArray(x)) {
		x = x.sort()
		return x.map(sortKeys);
	}
	return Object.keys(x).sort().reduce((o, k) => ({
		...o,
		[k]: sortKeys(x[k])
	}), {});
}

let tokenKeyName = ''
uni.addInterceptor('request', {
	invoke(args) {
		if (typeof args.data.merLogin != 'undefined') {
			tokenKeyName = 'mer_login_token'
		} else if (typeof args.data.serviceLogin != 'undefined') {
			tokenKeyName = 'service_login_token'
		} else {
			tokenKeyName = 'token'
		}
		args.header['X-Token'] = "Bearer " + Cache.get(tokenKeyName)
		if (Object.keys(args.data).length == 0) {
			return;
		}
		console.groupCollapsed(args.url)
		console.log(args)
		args.data.sign_random = uni.$u.guid(16)
		args.data.sign_time = ((new Date()).getTime() / 1000).toFixed()
		console.log(sortKeys(args.data));
		console.log(uni.$u.queryParams(sortKeys(args.data), false, 'brackets'))
		let x = JSON.stringify(sortKeys(args.data))
		// args.data.sign = md5(md5(uni.$u.queryParams(sortKeys(args.data), false,'brackets') + 'tjx') + args.data.sign_random)
		args.data.sign = md5(md5(JSON.stringify(sortKeys(args.data)) + 'tjx') + args.data.sign_random) //没时间调整签名
		console.groupEnd()
	},
	fail(err) {
		
	},
	success(res) {
		if (res.data.status == 410000 || res.data.status == 410001 || res.data.status ==
			410002 || res.data.status == 40000 || res.data.message == '请登录') {
			Cache.clear(tokenKeyName)
			switch (tokenKeyName) {
				case 'token':
					uni.navigateTo({
						url: "/pages/login/login"
					})
					break
				case 'mer_login_token':
					uni.navigateTo({
						url: "/P_merchant/login/login"
					})
					break
				case 'service_login_token':
					uni.navigateTo({
						url: "/P_service/login/login"
					})
					break
				default:
					uni.navigateTo({
						url: '/pages/index/index'
					})
			}
		}
	}
})
